package org.jgs1904.Semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author: 默苍璃
 * @date: 2024-11-05 17:59
 */
public class TestSemaphore {

    public static void main(String[] args) {
        final int numThreads = 3;
        final Semaphore semaphore = new Semaphore(2); // 创建一个许可证数量为2的信号量

        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(() -> {
                try {
                    semaphore.acquire(); // 获得许可证，如果没有可用的许可证会被阻塞
                    System.out.println("Thread " + Thread.currentThread().getName() + " has acquired the semaphore");
                    // 执行一些需要许可证的操作
                    Thread.sleep(2000);
                    semaphore.release(); // 释放许可证
                    System.out.println("Thread " + Thread.currentThread().getName() + " has released the semaphore");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }
    }
}
